<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no">
<meta name="description" content="">
<meta name="author" content="">
<!-- STYLESHEETS -->
<!--[if lt IE 9]><script src="../../js/flot/excanvas.min.js"></script><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script><![endif]-->
<link rel="stylesheet" type="text/css" href="../../css/cloud-admin.css" >
<link rel="stylesheet" type="text/css"  href="../../css/themes/default.css" id="skin-switcher" >
<link rel="stylesheet" type="text/css"  href="../../css/responsive.css" >	
<link href="../../font-awesome/css/font-awesome.min.css" rel="stylesheet">
<!-- file-input -->
<link rel="stylesheet" type="text/css"
	href="../../js/file-input/fileinput.css" />
<!-- SELECT2 -->
<link rel="stylesheet" type="text/css" href="../../js/select2/select2.min.css" />
<!-- UNIFORM -->
<link rel="stylesheet" type="text/css" href="../../js/uniform/css/uniform.default.min.css" />
<!-- datatable -->
<link rel="stylesheet" href="../../js/datatables/datatable.css">
<link rel="stylesheet" href="../../js/datepicker/datepicker.css">
<style type="text/css">
.wd{width: 110px}
.radio{width: 10px;display: inline;height: 25px;vertical-align: top;}
</style>
</head>
<body>
	<header class="navbar clearfix" id="header">
	</header>
	<!-- PAGE -->
	<section id="page">
		<!-- SIDEBAR -->
		<div id="sidebar" class="sidebar">
			<div class="sidebar-menu nav-collapse">
				<!-- SIDEBAR MENU -->
				<ul>
				</ul>
				<!-- /SIDEBAR MENU -->
			</div>
		</div>
		<!-- /SIDEBAR -->
		<div id="main-content">
			<div class="container">
				<div class="row">
					<div id="content" class="col-lg-12">
						<!-- PAGE HEADER-->
						<div class="row">
							<div class="col-sm-12">
								<div class="page-header">
									<!-- STYLER -->
									<!-- /STYLER -->
									<!-- BREADCRUMBS -->
									<ul class="breadcrumb">
										<li>
											<i class="fa fa-home"></i>
											<a href="index.html">首页</a>
										</li>
										<li>
											<a href="#">商品管理</a>
										</li>
										<li>维护商品</li>
									</ul>
									<!-- /BREADCRUMBS -->
								</div>
							</div>
						</div>
						<!-- /PAGE HEADER -->
						<!-- SAMPLE -->
						<div class="row col-md-12">
						<form id="form_weixin">
							<div class="form-group  mrg-bt10" >
								<input type="hidden" name="id"/>
								<label class="control-label col-md-3" style="line-height:34px;"><span class="required">*</span>模板类型：</label>
								<div class="col-md-5" style="display: inline-flex">
									<select id="messageType" name="templateId" class="col-md-8 select2-offscreen">
									</select>
								</div>
							</div>
							<!-- first.DATA -->
							<div class="form-group mrg-bt10" style="height: 70px;">
								<label class="control-label col-md-3" style="line-height:34px;"><span class="required">*</span>标题：</label>
								<div class="col-md-7" style="display: inline-flex">
									<textarea class="form-control " style="width:450px;height: 70px;" rows="7" cols="5" name="firstData" placeholder="请输入标题"></textarea>	
								</div>
							</div>
							<!-- keyword.DATA -->
							<div id="div_content">
							</div>
							<!--remark.DATA-->
							<div class="form-group mrg-bt10" style="height: 70px;">
								<label class="control-label col-md-3" style="line-height:34px;">备注：</label>
								<div class="col-md-7" style="display: inline-flex">
									<textarea class="form-control " style="width:450px;height: 70px;" rows="7" cols="5" name="remarkData" placeholder="请输入备注"></textarea>
								</div>
							</div>
							<!-- link.url -->
							<div class="form-group  mrg-bt10 linkUrl">
								<label class="control-label col-md-3"><span class="required">*</span>链接地址：</label>
								<div class="col-md-7" style="text-align: left;display: inline-flex">
									<input type="text" class="form-control" style="width:450px" name="linkUrl" placeholder="请输入链接地址">
									&nbsp;例：http://...										
								</div>
							</div>
							<!-- users -->
							<div class="form-group  mrg-bt10 users">
								<label class="control-label col-md-3"><span class="required">*</span>用户群体：</label>
								<div class="col-md-5" style="text-align: left;">
									<select id="userType" name="users" class="col-md-8 select2-offscreen">
										<option value="All">所有用户（关注且注册）</option>
										<!-- <option value="Vip">所有原女王</option> -->
										<option value="UserAgent">所有女王</option>
										<option value="NewCustomer">所有新客</option>
										<option value="UnOrder">指定时间之前下单且之后未下单用户</option>
										<option value="UnOrderWithRegister">注册之后未下单用户</option>
										<option value="UnUsedCouponAfterRegisterTime">指定优惠券（未使用未过期）的用户</option>
										<option value="SubscribeAndNotRegister">所有关注未注册用户</option>
										<option value="FromFile">其它（技术部提供用户id集文件）</option>
									</select>
									&nbsp;&nbsp;用户数：<span id="userCount">0</span>
									<input name="createBy" type="hidden"/>
								</div>
							</div>
							<!--startDate-->
							<div class="form-group  mrg-bt10 user_start">
								<label class="control-label col-md-3"></label>
								<div class="col-md-7" style="text-align: left;display: inline-flex">
									<input type="text" name="startDate"  class="form-control bootstrap-datepicker" 
										placeholder="限制开始时间" style="width:450px;margin-bottom: 20px;">
								</div>
							</div>
							<!--couponId-->
							<div class="form-group  mrg-bt10 couponId" style="display: none;">
								<label class="control-label col-md-3"></label>
								<div class="col-md-7" style="text-align: left;display: inline-flex">
									<input type="text" name="couponId"  class="form-control" 
										placeholder="券id（多个以英文逗号隔开）" style="width:450px;margin-bottom: 20px;">
								</div>
							</div>
							<!--user_id_file-->
							<div class="form-group  mrg-bt10 userIdFile" style="display: none;">
								<label class="control-label col-md-3"></label>
								<div class="col-md-7" style="text-align: left;display: inline-flex">
									<span class="btn btn-success btn-file" id="fir" style="margin-bottom: 20px;">
										<span id="two">导入用户id集</span> 
										<input name="uploadFile" upload-file="fileUrlUser" type="file">
									</span>
								</div>
							</div>
							<!-- test.mobile -->
							<div class="form-group  mrg-bt10 test">
								<label class="control-label col-md-3"><span class="required">*</span>测试手机号：</label>
								<div class="col-md-7" style="text-align: left;display: inline-flex">
									<input type="text" class="form-control"  style="width:450px" name="userName" placeholder="请输入您的手机号进行预览">										
								</div>
							</div>
						</form>
						<div class="row" style="height: 30px;">
							<div class="col-md-10" style="text-align: center;">
								<div class="box " style="color: red">
							 		 请先预览，预览没有问题再点 正式推送
								</div>
								<div class="box ">
									<a href="javascript:;" type="test"  class="btn btn-success bt-test" style="width: 100px;margin-top:20px;">
										预览
									</a>
									<a href="javascript:;" type="publish" class="btn btn-danger bt-publish" style="width: 100px;margin-top:20px;">
										正式推送
									</a>
								</div>
							</div>
				    	</div>		
						<!-- /SAMPLE -->
						<div class="footer-tools">
							<span class="go-top">
								<i class="fa fa-chevron-up"></i> Top
							</span>
						</div>
					</div>
					<!-- /CONTENT-->
				</div>
			</div>
		</div>
	</section>
	<!--/PAGE -->
	<!-- JAVASCRIPTS -->
	<!-- Placed at the end of the document so the pages load faster -->
	<script src="../../js/jquery/jquery-2.0.3.min.js"></script>
	<!-- JQUERY UI-->
	<script
		src="../../js/jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js"></script>
	<!-- BOOTSTRAP -->
	<script src="../../bootstrap-dist/js/bootstrap.min.js"></script>
	<!-- BLOCK UI -->
	<script type="text/javascript" src="../../js/jQuery-BlockUI/jquery.blockUI.min.js"></script>
	
	<!-- AUTOSIZE -->
	<script type="text/javascript" src="../../js/autosize/jquery.autosize.min.js"></script>
	<!-- spinner -->
		<script src="../../js/spinner/spin.js"></script>
	<!-- bootstrap-fileupload -->
	<script type="text/javascript"
		src="../../js/jquery-upload/js/jquery.iframe-transport.js"></script>
	<script type="text/javascript"
		src="../../js/jquery-upload/js/jquery.fileupload.min.js"></script>
	<script type="text/javascript"
		src="../../js/jquery-upload/js/jquery.fileupload-process.min.js"></script>
	<script type="text/javascript"
		src="../../js/jquery-upload/js/jquery.fileupload-validate.min.js"></script>
	<!-- INPUT MASK -->
	<script type="text/javascript" src="../../js/bootstrap-inputmask/bootstrap-inputmask.min.js"></script>
   	    <!--bootbox-->
	<script type="text/javascript" src="../../js/bootbox/bootbox.min.js"></script>
	<!-- SELECT2 -->
	<script type="text/javascript" src="../../js/select2/select2.min.js"></script>
	<!-- UNIFORM -->
	<script type="text/javascript" src="../../js/uniform/jquery.uniform.min.js"></script>
	<script type="text/javascript" src="../../js/datepicker/datepicker.js"></script>
	<script src="../../js/jquery-validate/jquery.validate.min.js"></script>
	<!-- COOKIE -->
	<script type="text/javascript" src="../../js/jQuery-Cookie/jquery.cookie.min.js"></script>
	<!-- CUSTOM SCRIPT -->
	<script src="../../js/script.js"></script>
    <script src="../../js/common.js"></script>
	<script>
		var weixin=function(){
			var templateData = new Map();
			var valiFrom=$("#form_weixin");
			var templateId = null;
			var templateTitle = null;
			var remarkData = '';
			var formValiInit=function(rules){
	        	valiFrom.validate({
	                doNotHideMessage: true,
					errorClass: 'error-span wd',
	                errorElement: 'span',
	                rules: rules,
	                highlight: function (element) { 
	                    $(element).closest('.form-group').removeClass('has-success').addClass('has-error'); 
	                },
	                unhighlight: function (element) { 
	                	$(element).closest('.form-group').removeClass('has-error'); 
	                },	
	                success: function (label) {
	                   	label.addClass('valid').closest('.form-group').removeClass('has-error').addClass('has-success'); 
	            	}
				});
			};
			var templateList = function() {
				$.ajax({
					type: "GET", 
					url: App.getContextPath() + "admin/weixin/findWeixinMessageList.do", 
					async: false, 
					success: function(result) {
						if (result.type == 'success' && result.extra != null) {
							$("#messageType").html('');
							$(result.extra).each(function(index, item) {
								$("#messageType").append('<option value="'+item.templateId+'">'+item.title+'</option>');
								templateData.set(item.templateId, item.keywordData);
							});
							$("#messageType").val(result.extra[0].templateId).trigger('change');
						}
					}
				});
			};
			var doSend = function(){
				var type=$(this).attr("type");
				var formJson = $("#form_weixin").serializeObject();
	        	if (valiFrom.valid() == false) {
	        		return false;
				}
	        	var templateTitle = $("#messageType").find(':selected').text();
	        	formJson.templateTitle = templateTitle;
				formJson.createTime = formJson.startDate;
				var createBy = formJson.users;
				var userType = $("#userType").val();
				if (userType === 'UnUsedCouponAfterRegisterTime') {
					createBy = createBy + "," + formJson.couponId; 
				}
				formJson.createBy = createBy; 
				delete formJson.users;
				delete formJson.startDate;
				delete formJson.couponId;
	        	if (type == "publish") {
        			$.confirm("确定将模板消息立即发送给指定用户吗?",function(){
        				formJson.userName="";
        				$.blockUI();
        				sendMsg(formJson,type);
        			});
        		} else if (type == "test") {
        			if (formJson.userName == "") {
        				$.alert("请输入手机号进行预览");
        				return false;
        			}
        			sendMsg(formJson, type);
        		}
			}
	        var bindClickPublish = function(){
	        	var dis = $(".bt-publish").attr("disabled");
	        	if("disabled" ==dis ){
					$(".bt-publish").removeAttr("disabled");
	        		$(".bt-publish").click(doSend);
	        	}
	        }
	        var offClickPublish = function(){
	       		$(".bt-publish").off("click");
			 	$(".bt-publish").attr("disabled","disabled");
	        }
			var sendMsg = function(formJson,type){	        	
				$.ajax({
					type: "post",
					url: App.getContextPath() + "admin/weixin/sendWeixinMessageFromTempalte.do",
					async: true,
					data: $.param({weixinMessage: JSON.stringify(formJson), userName: formJson.userName}),
					success: function(result) {
						if(type == "test" && result.type == "success") {
							bindClickPublish();
							$.alert("发送成功,请到手机上确认");
						}
						if (type == "publish" && result.type == "success") {
							$.alert("发送成功，发送用户数：" + result.extra);
							offClickPublish();
							$.unblockUI();
						} else {
							$.alert(result.content);
						}
					}
				});
			}
	    	var messageTypeChange = function(){
	    		$('[name=firstData]').val('');
				$('[name=remarkData]').val(remarkData);
				$('[name=linkUrl]').val('');
				$("#div_content").html('');
				templateId = $(this).val();
				$(templateData.get(templateId)).each(function(index, item){
					var div = $('<div class="form-group mrg-bt10"></div>');
					div.append('<label class="control-label col-md-3"><span class="required">*</span>'+item+'：</label>');
					div.append('<div class="col-md-7" style="text-align: left;display: inline-flex">'
						+'<input type="text" class="form-control" style="width:450px" name="keyword'+(index+1)+'Data" placeholder="请输入'+item+'">'
						+'</div>');
					$('#div_content').append(div);
				});
	    	}
			var getUserCount = function() {
				$(".couponId").hide();
				$(".userIdFile").hide();
				$(".user_start").show();
				var userType = $("#userType").val();
				var couponId = $("[name=couponId]").val();
				if (userType === 'UnUsedCouponAfterRegisterTime') {
					$(".couponId").show();
					if (couponId === '') {
						$("[name=createBy]").val('');
						$('#userCount').text(0);
						return;
					}
				} else if (userType === 'FromFile') {
					$(".userIdFile").show();
					$(".user_start").hide();
					$("[name=createBy]").val('');
					$('#userCount').text(0);
					return;
				} else if (userType === 'SubscribeAndNotRegister') {
					$(".user_start").hide();
				}
				var startDate = $('[name=startDate]').val();
				$.get(App.getContextPath() + "admin/weixin/getUserCount.do", {userType: userType, startDate: startDate, couponId: couponId}, function(result) {
					$('#userCount').text(result.extra);
				});
			}
			var fileUpload = function() {
				$("[upload-file=fileUrlUser]").fileupload({
					url: App.getContextPath() + "admin/weixin/getUserFromFile.do",
					dataType: 'json',
					acceptFileTypes: /(\.|\/)(txt)$/i,
					iframe: true,
					start: function (e) {
						$('.progress').fadeIn(300);
						return true;
					},
					autoUpload: true,
					done: function (e, data) {
						if (data.result.type == 'error') {
							$.alert("导入的数据有问题");
						} else if (data.result.extra && $.trim(data.result.extra) !== '') {
							$("[name=createBy]").val(data.result.extra);
							$('#userCount').text(data.result.extra.split(",").length);
						} else {
							$("[name=createBy]").val('');
							$('#userCount').text(0);
						}
					},
					progressall: function (e, data) {
						var progress = parseInt(data.loaded / data.total * 100, 10);
						$('.progress .progress-bar').css('width', progress + '%');
					}
				}).on('fileuploaddone', function (e, data) {
					$(".progress").fadeOut(300);
				});
			}
			var getRemark = function() {
				$.get(App.getContextPath() + "admin/coupon/getCouponPage.do", function(result) {
					remarkData = result.extra.title;
					$("[name=remarkData]").val(remarkData);
				});
			}
			return {	         
				init:function(){
					var startDate = $('[name=startDate]').bsdatepicker({
		    			format: 'yyyy-mm-dd',
		    			onRender: function(date) {
		    				var nowTemp = new Date();
		    				var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
							var startDate = new Date('2016-08-15');
		    				return date.valueOf() > now.valueOf() || date.valueOf() < startDate.valueOf() ? 'disabled' : '';
		    			}
		    		});
		    		startDate.bsdatepicker("setValue",function(){
		    			return '2016-08-15'
					}());	
		    		startDate.on('changeDate', function(ev) {    	 
		    			startDate.bsdatepicker("hide");
		    			updateAttentionCount();
		    		});
					$("#messageType").select2();
					$("#messageType").change(messageTypeChange);
					$("#userType").select2();
					$("#userType").change(getUserCount);
					$("[name=couponId]").blur(getUserCount);
		        	var rules={                	 
			        	firstData:{required:true},
			        	keyword1Data:{required:true},
	                	keyword2Data:{required:true},
	                	keyword3Data:{required:true},
	                	keyword4Data:{required:true},
	                	linkUrl:{required:true}
			        };
					formValiInit(rules);
					$(".bt-publish").attr("disabled","disabled");
					$(".bt-test").unbind("click").click(doSend);
		        	templateList();
					getUserCount();
					fileUpload();
					getRemark();
		     	}
			}
		}();
		$(function(){
			$("#header").load("../head.html");
			App.init(); //Initialise plugins and elements	        
	        weixin.init();
		});
	</script>
	<!-- /JAVASCRIPTS -->
</body>
</html>